import java.net.URL;
import java.util.List;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import com.google.gdata.client.Query;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.extensions.City;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.FamilyName;
import com.google.gdata.data.extensions.GivenName;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.data.extensions.PhoneNumber;
import com.google.gdata.data.extensions.PostCode;
import com.google.gdata.data.extensions.Street;
import com.google.gdata.data.extensions.StructuredPostalAddress;

public class Contacts {
	String[][] contacts_for_table;
	String[][] contacts;
	MainFrame frame;
	
	public Contacts (MainFrame mf){
		frame = mf;
	}
	
	public void retrieve_all_contacts(){
		try {
			ContactsService myService = new ContactsService("<var>js-photovoltaik</var>");
			myService.setUserCredentials("jsphotovoltaik@gmail.com","photovoltaik2012" );
			URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
			Query myQuery = new Query(feedUrl);
			myQuery.setStringCustomParameter("sortorder", "descending");
			ContactFeed resultFeed = myService.getFeed(myQuery, ContactFeed.class);
			List<ContactEntry> entries = resultFeed.getEntries();
			//Contacts for Table - [Last Name],[First Name],[City]
			contacts_for_table = new String[entries.size()][3];
			//Contacts Full - [Contact ID],[Last Name],[First Name],[Street],[City],[Postcode],[Primary Phone Number],[Secondary Phone Number],[eMail]
			contacts = new String[entries.size()][9];
			for (int i = 0; i < entries.size(); i++){
				contacts[i][0] = entries.get(i).getId().replace("http://www.google.com/m8/feeds/contacts/jsphotovoltaik%40googlemail.com/base/", "");
				
				Name name = entries.get(i).getName();
				if (name.hasFamilyName()){
					contacts_for_table[i][0] = name.getFamilyName().getValue();
					contacts[i][1] = name.getFamilyName().getValue();
				}else{
					contacts_for_table[i][0] = "";
					contacts[i][1] = "";
				}
				
				if (name.hasGivenName()){
					contacts_for_table[i][1] = name.getGivenName().getValue();
					contacts[i][2] = name.getGivenName().getValue();
				}else{
					contacts_for_table[i][1] = "";
					contacts[i][2] = "";
				}
				
				List<StructuredPostalAddress> spa = entries.get(i).getStructuredPostalAddresses();
				if (spa.size() > 0){
					if (spa.get(0).getStreet() != null){
						contacts[i][3] = spa.get(0).getStreet().getValue();
					}else{
						contacts[i][3] = "";
					}
					
					if (spa.get(0).getCity() != null){
						contacts_for_table[i][2] = spa.get(0).getCity().getValue();
						contacts[i][4] = spa.get(0).getCity().getValue();
					}else{
						contacts_for_table[i][2] = "";
						contacts[i][4] = "";
					}
					
					if (spa.get(0).getPostcode() != null){
						contacts[i][5] = spa.get(0).getPostcode().getValue();
					}else{
						contacts[i][5] = "";
					}
				}
				List<PhoneNumber> phoneNumbers = entries.get(i).getPhoneNumbers();
				switch(phoneNumbers.size()){
				
				case(0):	contacts[i][6] = "";
							contacts[i][7] = "";
							break;
				
				case(1):	contacts[i][6] = phoneNumbers.get(0).getPhoneNumber();
							contacts[i][7] = "";
							break;
							
				case(2):	contacts[i][6] = phoneNumbers.get(0).getPhoneNumber();
							contacts[i][7] = phoneNumbers.get(1).getPhoneNumber();
				}
				
				List<Email> email = entries.get(i).getEmailAddresses();
				if (email.get(0).getAddress() != null){
					contacts[i][8] = email.get(0).getAddress();
				}else{
					contacts[i][8] = "";
				}
				
			}
				  
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void deleteContact(int index){
		
		try {
			ContactsService myService = new ContactsService("<var>js-photovoltaik</var>");
			myService.setUserCredentials("jsphotovoltaik@gmail.com","photovoltaik2012" );
			
			URL userURL = new URL("https://www.google.com/m8/feeds/contacts/default/full/" + contacts[index][0]);
			ContactEntry contact = myService.getEntry(userURL, ContactEntry.class);
			contact.delete();
			retrieve_all_contacts();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void editContact(String[] contactEdit,int index){
		
		try {
			ContactsService myService = new ContactsService("<var>js-photovoltaik</var>");
			myService.setUserCredentials("jsphotovoltaik@gmail.com","photovoltaik2012" );
			
			URL userURL = new URL("https://www.google.com/m8/feeds/contacts/default/full/" + contacts[index][0]);
			ContactEntry contact = myService.getEntry(userURL, ContactEntry.class);
			
			contact.getName().getFamilyName().setValue(contactEdit[1]);
			contact.getName().getGivenName().setValue(contactEdit[2]);
			
			// TODO Hier werden alle vorhandenen Adressen gelöscht
			contact.getStructuredPostalAddresses().clear();
			
			// Neue Adresse hinzufügen
			StructuredPostalAddress spa = new StructuredPostalAddress();
			spa.setStreet(new Street(contactEdit[3]));
			spa.setCity(new City(contactEdit[4]));
			spa.setPostcode(new PostCode(contactEdit[5]));
			spa.setRel("http://schemas.google.com/g/2005#home");
			contact.getStructuredPostalAddresses().add(spa);
			

			contact.getPhoneNumbers().clear();
			
			if(!contactEdit[6].equals("")){
				PhoneNumber primaryPhoneNumber = new PhoneNumber();
			    primaryPhoneNumber.setPhoneNumber(contactEdit[6]);
			    primaryPhoneNumber.setRel("http://schemas.google.com/g/2005#home");
			    primaryPhoneNumber.setPrimary(true);
			    contact.addPhoneNumber(primaryPhoneNumber);
			}
			
			if(!contactEdit[7].equals("")){
				PhoneNumber secondaryPhoneNumber = new PhoneNumber();
				secondaryPhoneNumber.setPhoneNumber(contactEdit[7]);
				secondaryPhoneNumber.setRel("http://schemas.google.com/g/2005#work");
				contact.addPhoneNumber(secondaryPhoneNumber);
			}
			
			
			
			
			/*	
			int phoneNumberCount = 0;
			
			
			if (contactEdit[6] != ""){
				phoneNumberCount++;
			}
			
			if (contactEdit[7] != ""){
				phoneNumberCount++;
			}
			
			PhoneNumber primaryPhoneNumber = new PhoneNumber();
			PhoneNumber secondaryPhoneNumber = new PhoneNumber();
			
			switch(phoneNumberCount){
			
			case(0):	primaryPhoneNumber.setPhoneNumber("");
					    primaryPhoneNumber.setRel("http://schemas.google.com/g/2005#home");
					    primaryPhoneNumber.setPrimary(true);
					    contact.addPhoneNumber(primaryPhoneNumber);
					    
				    	secondaryPhoneNumber.setPhoneNumber("");
				    	secondaryPhoneNumber.setRel("http://schemas.google.com/g/2005#work");
				    	contact.addPhoneNumber(secondaryPhoneNumber);
					    
					    break;
					    
			case(1):	primaryPhoneNumber.setPhoneNumber(contactEdit[6]);
					    primaryPhoneNumber.setRel("http://schemas.google.com/g/2005#home");
					    primaryPhoneNumber.setPrimary(true);
					    contact.addPhoneNumber(primaryPhoneNumber);
					    
				    	secondaryPhoneNumber.setPhoneNumber("6666");
				    	secondaryPhoneNumber.setRel("http://schemas.google.com/g/2005#work");
				    	contact.addPhoneNumber(secondaryPhoneNumber);
					    
					    break;
					    
			case(2):	primaryPhoneNumber.setPhoneNumber(contactEdit[6]);
					    primaryPhoneNumber.setRel("http://schemas.google.com/g/2005#home");
					    primaryPhoneNumber.setPrimary(true);
					    contact.addPhoneNumber(primaryPhoneNumber);
					    
				    	secondaryPhoneNumber.setPhoneNumber(contactEdit[7]);
				    	secondaryPhoneNumber.setRel("http://schemas.google.com/g/2005#work");
				    	contact.addPhoneNumber(secondaryPhoneNumber);
					    
					    break;		
			}
			*/
		    
			contact.getEmailAddresses().clear();
			Email email = new Email();
		    email.setAddress(contactEdit[8]);
		    email.setRel("http://schemas.google.com/g/2005#home");
			contact.addEmailAddress(email);
		    

		    //Ausgabe zur Überprüfung
			for(int i = 0; i < contactEdit.length;i++){
				System.out.println(contactEdit[i]);
			}
			
			myService.update(userURL, contact);
			retrieve_all_contacts();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void addNewContact(String[] newContact){
		
		try {
			ContactsService myService = new ContactsService("<var>js-photovoltaik</var>");
			myService.setUserCredentials("jsphotovoltaik@gmail.com","photovoltaik2012" );
			
			ContactEntry contact = new ContactEntry();
			
			Name name = new Name();
			final String NO_YOMI = null;
			name.setFamilyName(new FamilyName(newContact[0], NO_YOMI));
			name.setGivenName(new GivenName(newContact[1], NO_YOMI));
			contact.setName(name);
			
			StructuredPostalAddress spa = new StructuredPostalAddress();
			spa.setStreet(new Street(newContact[2]));
			spa.setCity(new City(newContact[3]));
			spa.setPostcode(new PostCode(newContact[4]));
			spa.setRel("http://schemas.google.com/g/2005#home");
			contact.addStructuredPostalAddress(spa);
			
			if(newContact[5] != ""){
				PhoneNumber primaryPhoneNumber = new PhoneNumber();
				primaryPhoneNumber.setPhoneNumber(newContact[5]);
				primaryPhoneNumber.setRel("http://schemas.google.com/g/2005#home");
				primaryPhoneNumber.setPrimary(true);
				contact.addPhoneNumber(primaryPhoneNumber);
			}
			
			if(newContact[6] != ""){
				PhoneNumber secondaryPhoneNumber = new PhoneNumber();
				secondaryPhoneNumber.setPhoneNumber(newContact[6]);
				secondaryPhoneNumber.setRel("http://schemas.google.com/g/2005#work");
				contact.addPhoneNumber(secondaryPhoneNumber);
			}
			
			if(newContact[7] != ""){
				Email email = new Email();
				email.setAddress(newContact[7]);
				email.setRel("http://schemas.google.com/g/2005#home");
				contact.addEmailAddress(email);
			}
			
			URL postUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full");
			myService.insert(postUrl, contact);
			
			retrieve_all_contacts();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}

	public void updateContactTable (){
		JTable table_contacts = frame.getTableContacts();
		table_contacts.setModel(new DefaultTableModel(
			contacts_for_table,
			new String[]{
					"Nachname", "Vorname", "Ort"
			}
		));
	}
	
	public String[][] getContactsForTable(){
		return contacts_for_table;
	}
	
	public String[][] getContacts(){
		return contacts;
	}
	
}
